@file:Suppress("NOTHING_TO_INLINE")

package com.windea.study.kotlin.jvm.spam.extensions

import com.google.gson.*
import org.apache.http.*
import org.apache.http.client.methods.*
import org.apache.http.entity.*
import org.apache.http.impl.client.*

//考虑使用HttpClientBuilder，RequestBuilder

//@DslMarker
//annotation class HttpClientDsl


@PublishedApi internal val httpClient = HttpClientBuilder.create().build()

@PublishedApi internal val gson = Gson()


//inline fun get(uri: String) = HttpGet(uri)
//
//inline fun get(uri: String, vararg queryParams: Pair<String, Any?>) = HttpGet("$uri?${queryParams.toQueryString()}")
//
//
//inline fun post(uri: String) = HttpPost(uri)
//
//inline fun post(uri: String, vararg queryParams: Pair<String, Any?>) = HttpPost("$uri?${queryParams.toQueryString()}")
//
//inline fun post(uri: String, builder: HttpPost.() -> Unit) = HttpPost(uri).also(builder)
//
//inline fun post(uri: String, vararg queryParams: Pair<String, Any?>, builder: HttpPost.() -> Unit) =
//	HttpPost("$uri?${queryParams.toQueryString()}").also(builder)
//
//
//inline fun HttpEntityEnclosingRequestBase.body(body: Any) {
//	this.setHeader("Content-Type", "application/json;charset=utf8")
//	this.entity = StringEntity(gson.toJson(body), "UTF-8")
//}
//
//
//@PublishedApi
//internal fun Array<out Pair<String, Any?>>.toQueryString(): String {
//	return this.flatMap { (k, v) ->
//		if(v is List<*>) v.map { k to it }
//		else listOf(k to v)
//	}.joinToString("&") { (k, v) -> "$k=$v" }
//}

//////////////Builder extensions

fun RequestBuilder.addParameters(vararg params: Pair<String, String>): RequestBuilder {
	for(param in params) {
		this.addParameter(param.first, param.second)
	}
	return this
}

fun RequestBuilder.addBody(body: Any): RequestBuilder {
	this.setHeader("Content-Type", "application/json;charset=utf8")
	this.entity = StringEntity(gson.toJson(body), "UTF-8")
	return this
}


inline fun HttpUriRequest.response(): CloseableHttpResponse = httpClient.execute(this)

inline fun HttpUriRequest.response(httpClient: CloseableHttpClient): CloseableHttpResponse = httpClient.execute(this)

inline val CloseableHttpResponse.statusCode: Int? get() = this.statusLine?.statusCode

inline val CloseableHttpResponse.body: HttpEntity? get() = this.entity
